import { createApp, h, defineComponent, type VNode } from 'vue'
// import ConfirmDialog from '@/components/common/ConfirmDialog.tsx'
import ConfirmDialog from '@/components/common/ConfirmDialog.vue'

interface ConfirmDialogOptions {
  title: string
  content?: string | VNode | (() => VNode)
  confirmText?: string
  cancelText?: string
}

export function showConfirmDialog(options: ConfirmDialogOptions): Promise<void> {
  return new Promise((resolve, reject) => {
    const mountNode = document.createElement('div')
    document.body.appendChild(mountNode)

    let app: ReturnType<typeof createApp> | null = null

    const cleanup = () => {
      if (app) {
        app.unmount()
        app = null
      }
      if (mountNode && document.body.contains(mountNode)) {
        document.body.removeChild(mountNode)
      }
    }

    const handleConfirm = () => {
      cleanup()
      resolve()
    }

    const handleCancel = () => {
      cleanup()
      reject(new Error('Dialog cancelled')) // 或者 resolve(false)，根据你的需要决定
    }

    // 创建一个包装组件，以便可以传递 VNode 或渲染函数作为内容
    const DialogContentWrapper = defineComponent({
      render() {
        if (typeof options.content === 'function') {
          return options.content() // 如果是渲染函数，调用它
        } else if (typeof options.content === 'object' && options.content !== null) {
          return options.content // 如果是 VNode，直接返回
        } else {
          return h('p', options.content || '') // 如果是字符串或undefined，用p标签包裹
        }
      }
    })

    app = createApp({
      render() {
        return h(
          ConfirmDialog,
          {
            title: options.title,
            confirmText: options.confirmText,
            cancelText: options.cancelText,
            onConfirm: handleConfirm,
            onCancel: handleCancel
          },
          // 将内容作为默认插槽传递
          {
            default: () => h(DialogContentWrapper)
          }
        )
      }
    })

    app.mount(mountNode)
  })
}

// 简单示例，只传递字符串内容
export function showSimpleConfirmDialog(title: string, content: string): Promise<void> {
  return showConfirmDialog({ title, content })
}
